﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Accona.Monitoring.AppStatistics;
using Accona.Monitoring.Publishers;

namespace Accona.Monitoring.Consumers
{
    class MulticastConsumer
    {
        private MulticastReceiver receiver;

        public MulticastConsumer(string multicastGroup, int port)
        {
            receiver = new MulticastReceiver(multicastGroup,port);    
            receiver.OnMessage += ReceiveMessage;
        }

        private void ReceiveMessage(byte[] obj)
        {
            var stream = new MemoryStream(obj);
            var formatter = new BinaryFormatter();
            var deserializedObject = formatter.Deserialize(stream);
            var appstatistics = deserializedObject as AppStatisticsEvent;
            if (appstatistics!=null)
            {
                var memoryPublisher = Monitor.GetPublisher<MemoryPublisher>();
                memoryPublisher.Publish(appstatistics);
            }
        }
    }
}
